package saucaca.fragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.json.JSONException;

import saucaca.Adapter.AlbumAdapterListView;
import saucaca.Adapter.CustomAdapterVideoListview;
import saucaca.CustomView.ProgressBarCircularIndeterminate;
import saucaca.JSON.JsonReader;
import saucaca.JSON.WServiceLib;
import saucaca.Object.AlbumObject;
import saucaca.Object.AreaObject;
import saucaca.Object.HomeData;
import saucaca.Object.SongObject;
import saucaca.Util.TagName;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

import com.lemon.kenhnhacvn.BaseEngine;
import com.lemon.kenhnhacvn.MainActivity;
import com.lemon.kenhnhacvn.R;

public class BXHVideoFragment extends Fragment implements OnScrollListener {
	public static final String TAG = BXHVideoFragment.class.getSimpleName();
	private final static String VIDEO = "2";
	ArrayList<SongObject> songs;
	String areaCode = "";
	String week = "0";
	String authorCode = "";
	String page = "0";
	String pageSize = "10";
	String[] array_spinner_Week;
	String[] array_spinner_Area;
	String btype = VIDEO;
	int xpage = 0;
	boolean loadingMore;
	MainActivity mActivity;
	private ListView expandListview;
	private View mView_EmptyLoading = null;
	private ProgressBar progressBar;
	ImageView imgEmpty, imgError;
	TextView txtStatus;
	boolean isFromMenu;
	TextView txtTitle;
	CustomAdapterVideoListview adapter;
	private SwipeRefreshLayout mSwipeLayout;

	Spinner spinerWeekSong, spinerAreaSong;
	MyCustomAdapter adapterWeek, adapterArea;
	Calendar calendar;
	List<AreaObject> listArea;
	GetFromServices getFromServices;
	TextView textViewXemtoanbo;

	LinearLayout layoutHeader;
	ProgressBarCircularIndeterminate progressBarFooter;
	int m_PreviousTotalCount = 0;

//	public static BXHVideoFragment newInstance() {
//		BXHVideoFragment f = new BXHVideoFragment();
//		return f;
//	}
	BXHfragment bxHfragment;
	
	public static BXHVideoFragment newInstance(BXHfragment bxHfragment) {
		BXHVideoFragment f = new BXHVideoFragment(bxHfragment);
		return f;
	}
	
	public BXHVideoFragment(BXHfragment bxHfragment) {
		this.bxHfragment=bxHfragment;
	} 
	boolean checkString(String str) {
		if (str != null && !str.equals("")) {
			return true;
		} else
			return false;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mActivity = (MainActivity) getActivity();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View android = inflater.inflate(R.layout.listview2, container, false);
		findviewByID(android);
		addheaderview();
		sendRequest();
		return android;
	}

	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
	private void findviewByID(View view) {
		expandListview = (ListView) view.findViewById(R.id.layoutlistview_listview);
		mView_EmptyLoading = view.findViewById(R.id.empty_loading);
		expandListview.setEmptyView(mView_EmptyLoading);
		expandListview.setOnScrollListener(this);
		progressBar = (ProgressBar) mView_EmptyLoading.findViewById(R.id.empty_loading_progress);
		imgEmpty = (ImageView) mView_EmptyLoading.findViewById(R.id.empty_loading_NoItem);
		imgError = (ImageView) mView_EmptyLoading.findViewById(R.id.empty_loading_Error);
		txtStatus = (TextView) mView_EmptyLoading.findViewById(R.id.empty_loading_text);

		layoutHeader = (LinearLayout) view.findViewById(R.id.layout_header);
		progressBarFooter = (ProgressBarCircularIndeterminate) view.findViewById(R.id.progressBarloadmore);
		songs = new ArrayList<SongObject>();
		adapter = new CustomAdapterVideoListview(mActivity, songs, true);
		expandListview.setAdapter(adapter);
	}

	void addheaderview() {
		View view = getActivity().getLayoutInflater().inflate(R.layout.bxh_video_menu, null);
		spinerWeekSong = (Spinner) view.findViewById(R.id.BXH_spinner_week_video);
		spinerAreaSong = (Spinner) view.findViewById(R.id.BXH_spinner_Area_video);
		layoutHeader.addView(view);
		textViewXemtoanbo = (TextView) view.findViewById(R.id.artist_txtTopSong);
		textViewXemtoanbo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				BaseEngine.setVideoclick(mActivity, 0, songs);
			}
		});

		calendar = Calendar.getInstance();
		int s = calendar.get(Calendar.WEEK_OF_YEAR)-1;
		listArea = HomeData.homeListArea;
		array_spinner_Week = new String[s];
		for (int i = 0; i < s; i++) {
			array_spinner_Week[i] = "Tuần " + (s - i);
		}
		array_spinner_Area = new String[listArea.size()];
		for (int i = 0; i < listArea.size(); i++) {
			array_spinner_Area[i] = listArea.get(i).getTXNAME();
		}
		adapterWeek = new MyCustomAdapter(mActivity, R.layout.item_spinner, array_spinner_Week);
		adapterWeek.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		adapterArea = new MyCustomAdapter(mActivity, R.layout.item_spinner, array_spinner_Area);
		adapterArea.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		spinerWeekSong.setAdapter(adapterWeek);
		spinerAreaSong.setAdapter(adapterArea);

		spinerWeekSong.setOnItemSelectedListener(itemSelectedListener);
		spinerAreaSong.setOnItemSelectedListener(itemSelectedListener);
		
	}

	@Override
	public void setUserVisibleHint(boolean visible)
	{
	    super.setUserVisibleHint(visible);
//	    if (visible) {
//		}
	    if (visible && isResumed())
	    {
	        onResume();
	    }
	}
	
	
	public void onResume() {
		super.onResume();
		areaCode=bxHfragment.GetAreaCode();
		if (!areaCode.equals(""))
		for (int i = 0; i < array_spinner_Area.length; i++) {
			if(areaCode.equals(listArea.get(i).getAREA_CODE())){
				spinerAreaSong.setSelection(i);
				clear();
				areaCode = listArea.get(i).getAREA_CODE();
				bxHfragment.SetAreaCode(listArea.get(i).getAREA_CODE());
				sendRequest();
			}
		}
		
		week=bxHfragment.GetWeek();
		if (!areaCode.equals(""))
			for (int i = 0; i < array_spinner_Week.length; i++) {
				if(week.equals(""+i)){
					spinerWeekSong.setSelection(array_spinner_Week.length-i);
				}
			}
	};
	OnItemSelectedListener itemSelectedListener = new OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			switch (parent.getId()) {
			case R.id.BXH_spinner_week_video:
				clear();
				week = Integer.toString(array_spinner_Week.length - position);
				bxHfragment.SetWeek(week);
				sendRequest();
				break;
			case R.id.BXH_spinner_Area_video:
				clear();
				areaCode = listArea.get(position).getAREA_CODE();
				bxHfragment.SetAreaCode(listArea.get(position).getAREA_CODE());
				sendRequest();
				break;
			default:
				break;
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {

		}

	};

	void clear() {
		xpage = 0;
		songs.clear();
		adapter.update(songs);
		progressBar.setVisibility(View.VISIBLE);
		imgEmpty.setVisibility(View.GONE);
		txtStatus.setText("");
	}

	private void sendRequest() {
		if (getFromServices != null)
			getFromServices.cancel(true);
		getFromServices = new GetFromServices();
		getFromServices.execute("");
	}

	class GetFromServices extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... param) {
			if (m_PreviousTotalCount > 0)
				if (getActivity()!=null)
				getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						progressBarFooter.setVisibility(View.VISIBLE);
					}
				});
			String str = null;
			page = Integer.toString(xpage);
			loadingMore = true;
			str = WServiceLib.Bxh(btype, areaCode, week, page, pageSize);
//			BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result != null)
				try {
					if (getActivity()!=null)
					getActivity().runOnUiThread(new Runnable() {
						@Override
						public void run() {
							progressBarFooter.setVisibility(View.GONE);
						}
					});
					JsonReader.readHeader(result);
					if (HomeData.headerObject.getCODE().equals("0")) {
						ArrayList<SongObject> listsong = JsonReader.readlistSongFromString(result, TagName.KEY_BXH);
						for (int i = 0; i < listsong.size(); i++) {
							boolean isAdded = false;
							for (int j = 0; j < songs.size(); j++) {
								if (songs.get(j).getSONG_ID().equals(listsong.get(i).getSONG_ID())) {
									isAdded = true;
								}
							}
							if (!isAdded) {
								songs.add(listsong.get(i));
								adapter.update(songs);
							}
						}
					}
					if (songs == null || songs.size() == 0) {
						progressBar.setVisibility(View.GONE);
						imgEmpty.setVisibility(View.VISIBLE);
						txtStatus.setText(mActivity.getResources().getString(R.string.no_item_song));
					}
					loadingMore = false;
				} catch (JSONException e) {
					e.printStackTrace();
				}
		}

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if (totalItemCount == 0 || adapter == null)
			return;
		if (m_PreviousTotalCount == totalItemCount) {
			return;
		}
		boolean loadMore = firstVisibleItem + visibleItemCount >= totalItemCount - 3;
		if (loadMore && firstVisibleItem > 0 && totalItemCount - m_PreviousTotalCount >= 10) {
			m_PreviousTotalCount = totalItemCount;
			xpage += 1;
			new GetFromServices().execute("");
		}

	}

	public class MyCustomAdapter extends ArrayAdapter<String> {
		String[] objects;

		public MyCustomAdapter(Context context, int textViewResourceId, String[] objects) {
			super(context, textViewResourceId, objects);
			this.objects = objects;
		}

		@Override
		public View getDropDownView(int position, View convertView, ViewGroup parent) {
			return getCustomView(position, convertView, parent);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			return getCustomView(position, convertView, parent);
		}

		public View getCustomView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = mActivity.getLayoutInflater();
			View row = inflater.inflate(R.layout.item_spinner, parent, false);
			TextView label = (TextView) row.findViewById(R.id.spinner_text);
			label.setText(objects[position]);
			return row;
		}
	}
}